package com.banciyuan.bcywebview.biz.ask.question;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BasePullLoadActivity;
import com.banciyuan.bcywebview.base.factory.AskFactory;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.FlagUtils;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase.OnLastItemVisibleListener;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.setting.AskSettingActivity;
import com.banciyuan.bcywebview.biz.ask.answer.WriteAnswerActivity;
import com.banciyuan.bcywebview.biz.report.UserReportActivity;
import com.banciyuan.bcywebview.biz.share.block.BlockHelper;
import com.banciyuan.bcywebview.biz.share.block.IBlockHelper;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.Ask;
import de.greenrobot.daoexample.model.UserDetail;


/**
 * @author hfxt2008
 *         <p/>
 *         首页个人页面->ASK页面->问题页面
 */
public class QuestionActivity extends BasePullLoadActivity {
    public static int GO_WRITE_ANSWER = 1;
    private PullToRefreshListView mRefreshLv;
    private ListView mContentLv;
    private QuestionListviewAdapter mAdapter;
    private LoadingHelper mProgressbarHelper;

    private View mProgressbarView;
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;

    private QuestionHelper mHelper;
    private View viewParent;

    private int page = 1;
    private boolean is_load;
    private boolean is_end;
    private List<Ask> alist = new ArrayList<>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewParent = View.inflate(this, R.layout.question_layout, null);
        setContentView(viewParent);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    public void selfUpdateData() {
        mRefreshLv.setRefreshing();
    }

    @Override
    protected void initArgs() {
        mHelper = new QuestionHelper(this);
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.unansweredquestion));
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new LoadingHelper(viewParent);
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (!is_load) {
                    resetData();
                    mProgressbarHelper.onLoading();
                    initData();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }

    private void resetData() {
        is_load = true;
        is_end = false;
        page = 1;
    }

    @Override
    protected void initUi() {
        mRefreshLv = (PullToRefreshListView) findViewById(R.id.question_refresh_lv);
        mContentLv = mRefreshLv.getRefreshableView();
    }

    @Override
    protected void initAction() {
        mRefreshLv.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!is_load) {
                    resetData();
                    initData();
                }
            }
        });

        mRefreshLv.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!is_end && !is_load) {
                    is_load = true;
                    page++;
                    initData();
                }
            }
        });
        mContentLv.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        mHelper.getFrontData(UserDataHelper.getInstance(this).getToken(), page, new QuestionHelper.GetQuestionData() {
            @Override
            public void succ(String json) {
                try {
                    List<Ask> templist = AskFactory.createAsk(json);
                    renderQuestionData(templist);
                    renderNoDataView(templist);
                } catch (Exception e) {
                    onNetworkError();
                }
            }

            @Override
            public void fail(String fail) {
                onNetworkError();
            }
        });
    }

    private void renderNoDataView(List<Ask> templist) {
        if (page == 1 && templist.isEmpty()) {
            mProgressbarHelper.onNodata("", true);
            mRefreshLv.onRefreshComplete();
            is_load = false;
            is_end = true;
        }
    }

    private void renderQuestionData(List<Ask> templist) {
        if (page == 1) {
            FlagUtils.newAskNum = templist.size();
            alist.clear();
        }
        alist.addAll(templist);
        if (templist.size() == 0) {
            is_end = true;
        }
        if (mAdapter == null) {
            mAdapter = new QuestionListviewAdapter(this, alist);
            mContentLv.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        is_load = false;
    }

    public void doQuestionDel(final int position) {
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
        builder.setDescString(getString(R.string.not_respones_more))
                .setActionString(getString(R.string.comfirm))
                .setCancelString(getString(R.string.cancel_clear))
                .setActionClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mHelper.delQuestion(alist.get(position).getUa_id());
                        alist.remove(position);
                        mAdapter.updateData();
                    }
                })
                .create().show();
    }

    public void doBlockUser(final int position) {
        final BlockHelper blockHelper = new BlockHelper(new IBlockHelper() {
            @Override
            public void getSucc(String json) {
                MyToast.show(QuestionActivity.this, getString(R.string.block_succ));
            }

            @Override
            public void getFail() {

            }
        }, this);
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
        builder.setDescString(getString(R.string.enter_block_list))
                .setActionString(getString(R.string.comfirm_to_block_list))
                .setCancelString(getString(R.string.mydialog_cancel))
                .setActionClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        blockHelper.doBlock(UserDataHelper.getInstance(QuestionActivity.this).getToken(), alist.get(position).getCuid());
                    }
                }).create().show();
    }

    public void gotoReportUser(int position) {
        Intent intent = new Intent(this, UserReportActivity.class);
        UserDetail user = new UserDetail();
        user.setUid(alist.get(position).getCuid());
        user.setUname(alist.get(position).getCuname());
        intent.putExtra("user", user);
        startActivity(intent);
    }

    public void setAskAnonymous() {
        gotoUtil.gotoAct(this, AskSettingActivity.class);
    }

    public void onNetworkError() {
        is_load = false;
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onFailed();
    }

    public void gotoWriteAnswer(Ask ask) {
        Intent intent = new Intent(this, WriteAnswerActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, ask.getUa_id());
        intent.putExtra(gotoUtil.INTENT_VALUE_TWO, ask.getContent());
        startActivityForResult(intent, GO_WRITE_ANSWER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GO_WRITE_ANSWER && resultCode == RESULT_OK) {
            selfUpdateData();
        }
    }
}